package com.luo.gmall.cart.controller;

import com.luo.gmall.cart.entity.Cart;
import com.luo.gmall.cart.interceptor.LoginInterceptor;
import com.luo.gmall.cart.service.CartService;
import com.luo.gmall.common.bean.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Zoro
 * @date 2021年11月22
 */
@Controller
@Slf4j
public class CartController {



    @Autowired
    private CartService cartService;


    /**
     *  // 2.根据用户Id查询用户已选中的购物车记录
     * @param userId
     * @return
     */
    @GetMapping("list/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCheckCartsByUserId(@PathVariable("userId") Long userId){
        List<Cart> carts = cartService.queryCartsByUserId(userId);
        return ResponseVo.ok(carts);
    }


    /**
     * 将商品添加到购物车中的请求
     */
    @GetMapping
    public String toAddCart(Cart cart) {
        // 添加商品到购物车的方法
        cartService.addCart(cart);
        // 添加完成，重定向到回显页面
        return "redirect:http://cart.gmall.com/queryCart?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    @GetMapping("queryCart")
    public String queryCart(Cart cart, Model model) {
        // 获取添加时的cart中count
        BigDecimal count = cart.getCount();
        // 根据skuId获取cart数据信息
        Cart cartData = cartService.queryCart(cart);
        // 因为此时的cartData数据是从数据库中获取的，数量并不是添加时的数量，所以将数量改为添加时的那个数量
        cartData.setCount(count);
        // 将数据添加到model中
        model.addAttribute("cart", cartData);
        return "addCart";
    }


    /**
     * 查看购物车信息
     *
     * @return
     */
    @GetMapping("cart.html")
    public String queryCarts(Model model) {

        List<Cart> carts = cartService.queryCarts();
        model.addAttribute("carts", carts);
        return "cart";
    }

    /**
     * 修改购物车页面
     *
     * @return
     */
    @PostMapping("updateStatus")
    @ResponseBody
    public ResponseVo updateStatus(@RequestBody Cart cart) {
        cartService.updateStatus(cart);
        return ResponseVo.ok();
    }

    /**
     * 修改购物车商品数量
     *
     * @return
     */
    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart) {
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteCart(@RequestParam("skuId") Long skuId) {
        cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }


    @GetMapping("test")
    @ResponseBody
    public String test() {
//        log.info("handler方法执行登录状态：{}", loginInterceptor.getUserInfo().toString());

        long start = System.currentTimeMillis();
        log.info("① controller.test方法开始执行！");
        cartService.executor1();
        cartService.executor2();
//        ListenableFuture<String> future1 = cartService.executor1();
//        ListenableFuture<String> future2 = cartService.executor2();
//        try {
//            future1.addCallback(
//                    result -> log.info("execute1异步执行成功！{}", result),
//                    ex -> log.info("execute1异步执行失败！{}", ex.getMessage()));
//            future2.addCallback(
//                    result -> log.info("execute2异步执行成功！{}", result),
//                    ex -> log.info("execute2异步执行失败！{}", ex.getMessage()));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        log.info("② controller.test方法执行结束！时间：{}", System.currentTimeMillis() - start);

        return "hello cart!";
    }

    @Async
    public String executor1() {
        log.info("② executor1开始执行。。。");
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("③ executor1开始执行结束。。");
        return "executor1";
    }

    @Async
    public String executor2() {
        log.info("④ executor2开始执行。。。");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("⑤ executor2开始执行结束。。。");
        return "executor2";
    }
}
